<script setup lang="ts">
import type { RoleItem } from '#/views/system/role/role.data';

import { ref } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';

import { useRequestRole } from '#/api/core/api';
import { addUserRole, deleteUserRole, getUserBYRoleId } from '#/api/core/user';
import UserSelector from '#/components/business/UserSelector.vue';
import BasisTable from '#/components/table/BasisTable.vue';

import { roleUserDrawerColumns } from './role.data';

interface RoleUser {
  username: string;
  nickname: string;
  phone: string;
  email: string;
  status: string;
}
const { useRequestHandle } = useRequestRole;
const userSelector = ref<InstanceType<typeof UserSelector>>();
const roleId = ref<number | string>();
const drawerVisible = ref(false);
const loading = ref(false);
const dataList = ref<RoleUser[]>([]);

const handleSelectUser = () => {
  userSelector.value?.open({ type: 'role', id: roleId });
};

// 获取角色用户列表
const fetchRoleUsers = async () => {
  if (!roleId.value) return;

  try {
    loading.value = true;
    dataList.value = await getUserBYRoleId(roleId.value);
  } catch (error) {
    console.error('获取角色用户列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 打开抽屉
const openDrawer = async (id: number | string) => {
  drawerVisible.value = true;
  roleId.value = id;
  await fetchRoleUsers();
};
const addRuleUser = async (userList: any[]) => {
  try {
    loading.value = true;
    const userIds = userList.map((item) => item.userId);
    await addUserRole({
      roleId: roleId.value,
      userIds,
    });
    await fetchRoleUsers();
  } catch (error) {
    console.error('添加角色用户失败:', error);
  } finally {
    loading.value = false;
  }
};
const refresh = async () => {
  await fetchRoleUsers();
};

// 删除角色用户
const handleDeleteUserRole = (row: RoleItem) => {
  ElMessageBox.confirm(`确认要取消关联吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteUserRole({
        roleId: roleId.value,
        userId: row.userId,
      });
      ElMessage.success('取消功');
      refresh();
    } catch {
      ElMessage.error('取消失败');
    }
  });
};

defineExpose({
  openDrawer,
});
</script>

<template>
  <el-drawer
    v-model="drawerVisible"
    :close-on-click-modal="false"
    size="800px"
    title="角色用户"
  >
    <BasisTable
      :columns="roleUserDrawerColumns"
      :data="dataList"
      :loading="loading"
      :show-toolbar="true"
      height="calc(100vh - 200px)"
    >
      <!-- 工具栏左侧插槽 -->
      <template #toolbar-left>
        <el-button type="primary" @click="handleSelectUser">
          已有用户
        </el-button>
      </template>
      <!-- 状态列 -->
      <template #status="{ row }">
        <el-tag :type="row.status === '0' ? 'success' : 'danger'">
          {{ row.status === '0' ? '正常' : '停用' }}
        </el-tag>
      </template>
      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button link type="primary" @click="handleDeleteUserRole(row)">
          取消关联
        </el-button>
      </template>
    </BasisTable>
    <UserSelector
      ref="userSelector"
      multiple
      @update:model-value="addRuleUser"
    />
  </el-drawer>
</template>

<style scoped>
:deep(.el-drawer__body) {
  padding: 0;
}
</style>
